import Taro from '@tarojs/taro'
import { BASE_URL as baseUrl,customeAppId } from './serviceSwitching';
import currentEnv from "../../configure/currentEnv"

let merchantId = sassAppId == '0'?'0':'1736643239079055361';
if(customeAppId == '8glai7') merchantId = '1928393761174589442' // 苏宁影城
if(customeAppId == 'bc5mi9') merchantId = '1633675580264419329' ///  保利
if(customeAppId == '9f5c9t') merchantId = '1862153744672886786' // 苏宁影城
if(customeAppId == 'ixy0jd') merchantId = '1960897145865506818' // Ulive超生活
let BASE_URL = baseUrl,ENV,sassAppId = customeAppId,
channel = `${currentEnv.project=='yingjing'?'activity':'cinema'}-weixin-h5`;
if(process.env.TARO_ENV === 'weapp') channel = `${currentEnv.project=='yingjing'?'activity-weixin':'cinema-wechat'}-mini`
if(process.env.TARO_ENV === 'tt') channel = `${currentEnv.project=='yingjing'?'event':'cinema'}-douyin-mini`
if(process.env.TARO_ENV === 'alipay') channel = `${currentEnv.project=='yingjing'?'activity':'cinema'}-alipay-mini`
let joinApi = process.env.TARO_ENV == 'h5'
if(process.env.TARO_ENV === 'h5'){
  const Vconsole = require('@/utils/vconsole.min.js')
  if(process.env.NODE_ENV == 'production'){
    sassAppId = location.pathname.split('/')[2]
    joinApi = false
    if(location.hostname == 'sit.m.fenxian.com'){
      new Vconsole()
      BASE_URL = 'https://sit.api.tuan.ant.shop'
      ENV = 'sitactivity'
    }else{
      BASE_URL = 'https://api.tuan.ues.xyz'   //   正式
      ENV = 'prodevent'
    }
  }else{
    new Vconsole()
    BASE_URL = ''
    joinApi = true
  }
}

const get = async (url, params, load, config = {}) =>{
  return await new Promise((resolve,reject)=>{
    Taro.request({
      url: BASE_URL + `${joinApi?'/api':''}` + url,
      data: params,
      timeout: 300000,
      method: 'GET',
      header: {
        channel,
        sassAppId,
        token:Taro.getStorageSync('token'),
        merchantId,
        ...config,
      },
      success: res => {
        console.log('请求成功',BASE_URL + url,res.data,params)
        const {code} = res.data
        if(code == 401){
          Taro.handleLogin('back')
          return;
        }
        resolve(res.data)
        /** end 处理结束*/
      },
      fail: error => {
        reject(error)
      },
      complete:res=>{
        if(load) Taro.hideLoading();
      }
    })
  })
}

const post = async (url, params, load, config = {}) =>{
  return await new Promise((resolve,reject)=>{
    Taro.request({
      url: BASE_URL + `${joinApi?'/api':''}` + url,
      data: params,
      timeout: 300000,
      method: 'POST',
      header: {
        channel,
        sassAppId,
        merchantId,
        token:Taro.getStorageSync('token'),
        ...config,
      },
      success: res => {
        console.log('请求成功',BASE_URL + url,res.data,params)
        const {code} = res.data
        if(code == 401){
          Taro.handleLogin('back')
          return;
        }
        resolve(res.data)
        /** end 处理结束*/
      },
      fail: error => {
        reject(error)
      },
      complete:res=>{
        if(load) Taro.hideLoading();
      }
    })
  })
}

const put = async (url, params, load, config = {}) =>{
  return await new Promise((resolve,reject)=>{
    Taro.request({
      url: BASE_URL + `${joinApi?'/api':''}` + url,
      data: params,
      timeout: 300000,
      method: 'PUT',
      header: {
        channel,
        sassAppId,
        merchantId,
        token:Taro.getStorageSync('token'),
        ...config,
      },
      success: res => {
        console.log('请求成功',params)
        const {code} = res.data
        if(code == 401){
          Taro.handleLogin('back')
          return;
        }
        resolve(res.data)
        /** end 处理结束*/
      },
      fail: error => {
        reject(error)
      },
      complete:res=>{
        if(load) Taro.hideLoading();
      }
    })
  })
}

export const uploadFile = ({ file, config }) => {
  return new Promise((resolve) => {
    let formData = {};
    const filePath =
      config.dir + parseInt(Date.parse(new Date()) + Math.random() * 100000) + '.jpg';
    Object.assign(formData, {
      key: filePath,
      OSSAccessKeyId: config.accessid,
      policy: config.policy,
      Signature: config.signature,
    });
    Taro.uploadFile({
      url: config.host,
      filePath: file,
      name: 'file',
      header: {
        token: Taro.getStorageSync('token'),
        channel,
      },
      formData,
      withCredentials:false,
      fail() {
        resolve({});
      },
      success() {
        resolve({ code: 1, content: config.host + '/' + filePath });
      },
    });
    // }).catch(()=>{
    //   resolve({});
    // });
  });
};

export default (
  options = {
    method: 'GET',
    data: {},
    unNeedToken: false,
    fullResponse: false,
    mode: 'same-origin',
    cache: 'default',
  },
) => {
  let header = {
    'Content-Type': 'application/json',
    channel,
    sassAppId,
    merchantId,
  };

  let token = Taro.getStorageSync('token')
  if (token == false) {
    token = '';
  }
  header['token'] = token;

  if (options.headers) {
    header = {
      ...header,
      ...options.headers,
    };
  }

  return Taro.request({
    url: (options.baseUrl || BASE_URL) + `${joinApi?'/api':''}` + options.url,
    data: Array.isArray(options.data)
      ? [...options.data]
      : {
          ...options.data,
        },
    header,
    method: options.method.toUpperCase(),
    mode: options.mode,
    cache: options.cache,
    fail: (e) => {
      let tip = '';
      if (e.errMsg?.indexOf('request:fail') === 0) {
        tip = '网络不给力，请检查网络';
      } else if (e.error === 'Internal Server Error' && e.status === 500) {
        tip = '服务器内部错误';
      } else if (e.status === 504) {
        tip = '服务器繁忙，请稍后再试';
      }
      let currentPages = Taro.getCurrentPages();
      let lastPage = currentPages[currentPages.length - 1];
      if (tip.length > 0) {
        if (
          lastPage.route?.indexOf('pages/mainPages/homePage/homePage') == 0 ||
          lastPage.route?.indexOf('pages/mainPages/me/index') == 0 ||
          lastPage.route?.indexOf('pages/mainPages/cart/index') == 0
        ) {
          Taro.setStorageSync('unusualInfo', {
            tip,
            route: '/' + lastPage.route,
          });
        } else {
          let params = '';
          if (lastPage.options) {
            params += '?';
            for (let key in lastPage.options) {
              params += key + '=' + lastPage.options[key] + '&';
            }
            params = params.slice(0, -1);
          }
          // Taro.navigateTo({
          //   url: `/mainPages/unusual/index?tip=${tip}&url=${encodeURIComponent(
          //     '/' + lastPage.route + params,
          //   )}`,
          // });
        }
      }
    },
  })
    .then((res) => {
      console.log('请求成功--',BASE_URL + options.url,res.data,options.data)
      // 对请求结果完整返回, 不做处理
      if (options.fullResponse) {
        return res;
      }
      const { statusCode, data={} } = res;
      if (statusCode >= 200 && statusCode < 300) {
        if (data.code != '1') {
          if (
            data.code === '401' ||
            (data.code === '400' && data.message === 'Token can not be null')
          ) {
            if (data.message === 'token已失效') {
              Taro.removeStorageSync('user');
            }
            Taro.showToast({
              title: `请重新登录`,
              icon: 'none',
              mask: true,
              duration: 1000,
            });
            setTimeout(() => {
              Taro.handleLogin('back')
            }, 500);
          } else if (options.noToast !== true) {
            Taro.showToast({
              title: `${res.data.message}` || res.data.code,
              icon: 'none',
              mask: true,
              duration: 1500,
            });
          }
        }
        return data;
      } else if (statusCode == 401) {
        Taro.removeStorageSync('user');
        Taro.showToast({
          title: '已过期，请重新登录',
          icon: 'none',
          mask: true,
        });
        setTimeout(() => {
          Taro.handleLogin('back')
        }, 500);
      }else{
        return data;
      }
    })
};

export {BASE_URL,ENV,channel,get,post,put,sassAppId}